package com.yanyq.message.m1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.List;
/**
 * 消息订阅者
 */
public class Subscriber implements Runnable{
    private String path;
    private ZooKeeper zk = ZkUtil.getZk();

    public Subscriber(String path){
        this.path = path;
    }

    public void subScribe(final String name){
        try {
            zk.getChildren(path,new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    Event.EventType t = event.getType();
                    //只有子节点被改变(子节点被删除或者新增)才会通知它,所以在这里不做判断
                    System.out.println("我是消息订阅者["+name+"],当前发生的事件是:"+t);
                    try {
                        List<String> children = zk.getChildren(path, false);
                        System.out.println("我是消息订阅者["+name+"],当前的子节点是:"+children);
                    } catch (KeeperException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    //一次注册事件完成后再次注册,当然上面的代码只是演示注册事件接到通知后的demo,实际业务要比这个复杂的多
                    subScribe(name);
                }
            });
        }catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run(){
        subScribe(Thread.currentThread().getName());
    }
}
